import React, { useEffect, useState } from 'react';
import { Form, Input, Button, ImageUploader, TextArea, Switch, Image } from 'antd-mobile';
import styles from './index.module.less';
import HeaderNav from "@/components/header-nav";
import { useSearchParams } from 'react-router-dom';
const { getUserWorldBookDetails, getCategory, publishWorldRole } = $globalServicer('world')
import { handleImageUpload } from '@/utils/upload';
import TagSelector from '@/components/TagSelector';
import { showErrorToast, showSuccessToast } from '@/utils/customToast';


const Publish = () => {

  const [roleForm] = Form.useForm();
  const [params] = useSearchParams();
  const id = params.get('id');
  const [submitting, setSubmitting] = useState(false)
  const [options, setOptions] = useState([])
  const [cardInfo, setCardInfo] = useState(null);
  const [cid, setCid] = useState(null)
  const [loading, setLoading] = useState(true)
  const [showCategoryDropdown, setShowCategoryDropdown] = useState(false)
  const [selectedCategory, setSelectedCategory] = useState(null)
  const [collapsedCategories, setCollapsedCategories] = useState(new Set())

  useEffect(() => {
    if (id) {
      getUserWorldBookDetails(id).then(res => {
        console.log('接口返回的数据:', res);
        setCardInfo(res);
        // 设置表单初始值
        const formData = {
          home_cover: res.home_cover || res.cover,
          home_name: res.home_name || res.name,
          home_description: res.home_description || res.description?.content || res.description,
          push_reason: res.push_reason || '推荐这个智能体',
          publish_type: res.publish_type || true
        };

        console.log('设置表单初始值:', formData);
        roleForm.setFieldsValue(formData);
        if (res.type === 2) {
          roleForm.setFieldsValue({ roles: res.npcs })
        } else {
          roleForm.setFieldsValue({
            roles: [{
              id: 0,
              desc: '',
            }]
          })
        }
        setLoading(false);
      });

      getCategory().then(res => {
        const options = formatOption(res.data);
        setOptions(options);
      });
    } else {
      setLoading(false);
    }
  }, [])

  // 格式化/反查 分类选项 type:1格式化 type:2反查
  const formatOption = (data, type = 1, ids) => {
    if (type === 1) {
      return data.map(item => ({
        label: item.name,
        value: item.id,
        is_selectable: item.is_selectable,
        children: item.children && item.children.length ? formatOption(item.children) : undefined
      }))
    } else if (ids) {
      let id = ids.shift()
      let values = data.filter(item => item.value == id)
      if (ids.length) {
        let child = formatOption(values[0].children, 2, ids)
        values = [...values, ...child]
      }
      return values
    }
  }

  // 展示分类选择
  const showCascader = () => {
    setShowCategoryDropdown(!showCategoryDropdown)
  }

  // 选择分类
  const handleCategorySelect = (category) => {
    // 检查是否可选择
    if (category.is_selectable === 1) {
      return; // 不可选择，直接返回
    }
    setSelectedCategory(category)
    roleForm.setFieldsValue({ category_id: category.value })
  }

  // 选择子分类
  const handleSubcategorySelect = (subcategory, parentCategory) => {
    // 检查是否可选择
    if (subcategory.is_selectable === 1) {
      return; // 不可选择，直接返回
    }
    setSelectedCategory({
      ...subcategory,
      parentLabel: parentCategory.label
    })
    setShowCategoryDropdown(false)
    roleForm.setFieldsValue({ category_id: subcategory.value })
  }

  // 切换分类折叠状态
  const toggleCategoryCollapse = (categoryName, event) => {
    event.stopPropagation()
    event.preventDefault()
    setCollapsedCategories(prev => {
      const newSet = new Set(prev)
      if (newSet.has(categoryName)) {
        newSet.delete(categoryName)
      } else {
        newSet.add(categoryName)
      }
      return newSet
    })
  }

  // 点击外部关闭下拉列表
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (showCategoryDropdown && !event.target.closest(`.${styles.inputGroup}`)) {
        setShowCategoryDropdown(false)
      }
    }

    if (showCategoryDropdown) {
      document.addEventListener('mousedown', handleClickOutside)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [showCategoryDropdown])

  // 处理发布按钮点击
  const handlePublishClick = () => {
    console.log('发布按钮被点击');
    console.log('当前表单值:', roleForm.getFieldsValue());
    console.log('cardInfo:', cardInfo);
    console.log('submitting:', submitting);

    // 手动触发表单验证
    roleForm.validateFields().then(values => {
      console.log('表单验证通过:', values);
      onFinish(values);
    }).catch(errorInfo => {
      console.log('表单验证失败:', errorInfo);
      showErrorToast('请填写完整信息');
    });
  };

  const onFinish = (values) => {
    if (submitting) return; // 如果正在提交，直接返回

    // 检查必要的数据是否存在
    if (!cardInfo || !cardInfo.id) {
      showErrorToast('数据加载中，请稍后再试');
      return;
    }

    const subData = {
      ...values,
      home_cover: values.home_cover?.[0]?.url || cardInfo.home_cover || cardInfo.cover || '',
      home_name: values.home_name?.trim() || cardInfo.home_name || cardInfo.name || '',
      home_description: values.home_description?.trim() || cardInfo.home_description || cardInfo.description?.content || cardInfo.description || '',
      push_reason: values.push_reason?.trim() || '推荐这个智能体',
      publish_type: 2,
      roles: values.roles?.map((role, index) => ({
        id: cardInfo.type == 2 ? (cardInfo.npcs?.[index]?.id || 0) : 0, // 非世界卡分享，id为0
        desc: role.desc?.trim() || '',
      })) || [],
      id: cardInfo.id,
      type: cardInfo.type
    }
    if(cardInfo.type == 3 && subData.roles?.length == 0) {
      subData.roles=[
        {
          id:0,
          desc:subData.home_description
        }
      ]
    }
    console.log("🚀 ~ onFinish ~ submitData:", values, subData)
    setSubmitting(true);
    publishWorldRole(subData).then(res => {
      showSuccessToast('智能体上传成功，请等待审核');
      history.back()
    }).catch(err => {
      console.error('发布失败:', err);
      showErrorToast('智能体发布失败，请检查网络');
    }).finally(() => {
      setSubmitting(false);
    })
  };

  return (
    <div className={styles.formContainer}>
      {/* 头部 */}
      <header className={styles.header}>
        <button className={styles.backButton} onClick={() => history.back()}>
          <i className="material-icons">arrow_back_ios_new</i>
        </button>
        <h1 className={styles.title}>上传智能体</h1>
        <Button
          className={styles.publishButton}
          onClick={handlePublishClick}
          loading={submitting}
          disabled={submitting}
        >
          {submitting ? '发布中...' : '发布'}
        </Button>
      </header>

      <main className={styles.main}>
        <Form
          form={roleForm}
          onFinish={onFinish}
          className={styles.form}
        >
          {/* 智能体信息展示 */}
          <div className={styles.agentInfo}>
            <div className={styles.avatarContainer}>
              {/* 直接显示图片 */}
              {loading ? (
                <div
                  style={{
                    width: 128,
                    height: 128,
                    borderRadius: '50%',
                    border: '4px solid #374151',
                    backgroundColor: '#2c2c2c',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: '#9ca3af'
                  }}
                >
                  加载中...
                </div>
              ) : (
                <Image
                  src={(() => {
                    // 处理图片路径，检查多个可能的字段
                    let imageSrc = '';

                    // 优先检查 home_cover
                    if (cardInfo?.home_cover) {
                      if (Array.isArray(cardInfo.home_cover)) {
                        imageSrc = cardInfo.home_cover[0]?.url || cardInfo.home_cover[0] || '';
                      } else {
                        imageSrc = cardInfo.home_cover;
                      }
                    }
                    // 检查 cover 字段
                    else if (cardInfo?.cover) {
                      if (Array.isArray(cardInfo.cover)) {
                        imageSrc = cardInfo.cover[0]?.url || cardInfo.cover[0] || '';
                      } else {
                        imageSrc = cardInfo.cover;
                      }
                    }
                    // 检查世界卡的角色头像
                    else if (cardInfo?.type === 2 && cardInfo?.npcs?.[0]?.cover) {
                      imageSrc = cardInfo.npcs[0].cover;
                    } else {
                      imageSrc = '/default-avatar.png';
                    }

                    console.log('图片src:', imageSrc);
                    console.log('cardInfo:', cardInfo);
                    return imageSrc;
                  })()}
                  width={128}
                  height={128}
                  fit='cover'
                  style={{ borderRadius: '50%', border: '4px solid #374151', boxShadow: '0 4px 14px 0 rgba(0, 0, 0, 0.3)' }}
                />
              )}
              {/* 隐藏的表单字段，用于数据提交 */}
              <Form.Item name="home_cover" style={{ display: 'none' }}>
                <Input />
              </Form.Item>
            </div>
            {/* 角色名称显示 */}
            {!loading && cardInfo && cardInfo.type === 2 && cardInfo.npcs && cardInfo.npcs.length > 0 && (
              <p className={styles.roleName}>{cardInfo.npcs[0].name}</p>
            )}
            {/* 卡片名称显示 */}
            {!loading && cardInfo && (cardInfo.home_name || cardInfo.name) && (
              <p className={styles.cardTitle}>{cardInfo.home_name || cardInfo.name}</p>
            )}
            {/* 作者信息显示 */}
            {!loading && cardInfo && (
              <p className={styles.author}>@{cardInfo.user_name || cardInfo.user_name || '开发者'}</p>
            )}
            {/* 隐藏的表单字段，用于数据提交 */}
            <Form.Item name="home_name" style={{ display: 'none' }}>
              <Input />
            </Form.Item>
          </div>
          {/* 分类选择 */}
          <div className={styles.inputGroup}>
            <label className={styles.label}>分类</label>
            <Form.Item name="category_id" rules={[{ required: true, message: '请选择分类' }]}>
              <div className={styles.categoryInput} onClick={showCascader}>
                <i className="material-icons">widgets</i>
                <span className={styles.categoryText}>
                  {selectedCategory ? `${selectedCategory.parentLabel}-${selectedCategory.label}` : '请选择分类名称'}
                </span>
                <span className={styles.dropdown_arrow}>
                  {showCategoryDropdown ? '▲' : '▼'}
                </span>
              </div>
              
              {showCategoryDropdown && (
                <div className={`${styles.category_dropdown} ${styles.dropdown_enter}`}>
                  <div className={styles.dropdown_content}>
                    {options.length > 0 ? (
                      options.map((category) => {
                        const isCollapsed = collapsedCategories.has(category.label)
                        return (
                          <div key={category.value} className={styles.category_item}>
                            <div 
                              className={`${styles.category_header} ${category.is_selectable === 1 ? styles.disabled_category : ''}`}
                              onClick={() => {
                                if (category.children && category.children.length > 0) {
                                  toggleCategoryCollapse(category.label, { preventDefault: () => {}, stopPropagation: () => {} })
                                }
                              }}
                            >
                              <div className={styles.category_title_wrapper}>
                                <span className={`${styles.category_name} ${category.is_selectable === 1 ? styles.disabled_text : ''}`}>
                                  {category.label}
                                </span>
                              </div>
                              {category.children && category.children.length > 0 && (
                                <span className={`${styles.category_arrow} ${isCollapsed ? styles.collapsed : ''}`}>
                                  ▼
                                </span>
                              )}
                            </div>
                            {!isCollapsed && category.children && category.children.length > 0 && (
                              <div className={styles.subcategories_list}>
                                {category.children.map((subcategory) => (
                                  <div
                                    key={subcategory.value}
                                    className={`${styles.subcategory_item} ${subcategory.is_selectable === 1 ? styles.disabled_subcategory : ''}`}
                                    onClick={() => handleSubcategorySelect(subcategory, category)}
                                  >
                                    <span className={`${styles.subcategory_name} ${subcategory.is_selectable === 1 ? styles.disabled_text : ''}`}>
                                      {subcategory.label}
                                    </span>
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                        )
                      })
                    ) : (
                      <div className={styles.loading_categories}>
                        <span>加载分类中...</span>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </Form.Item>
          </div>

          {/* 简介输入 */}
          <div className={styles.inputGroup}>
            <label className={styles.label}>简介</label>
            <Form.Item name="home_description" rules={[{ required: true, message: '卡片描述不能为空' }]}>
              <div className={styles.descriptionContainer}>
                <i className="material-icons">description</i>
                <TextArea
                  className={styles.descriptionInput}
                  placeholder="请添加简介..."
                  rows={5}
                  maxLength={500}
                />
              </div>
            </Form.Item>
          </div>

          {/* 隐藏的私密设置，默认为私密 */}
          <Form.Item name="publish_type" initialValue={true} style={{ display: 'none' }}>
            <Switch />
          </Form.Item>

          {/* 推荐理由 */}
          <Form.Item name="push_reason" style={{ display: 'none' }}>
            <Input />
          </Form.Item>

        </Form>
      </main>
    </div>
  );
}

export default Publish;